<template>
    <div class="user-list-container">
      <div class="header">
        <div class="search-filters">
          <div class="filter-item">
            <label for="startDate" style="color: black;">创建时间：</label>
            <input type="date" id="startDate" v-model="startDate">
          </div>
          <div class="filter-item">
            <label for="endDate"></label>
            <input type="date" id="endDate" v-model="endDate">
          </div>
          <div class="filter-item">
            <label for="inputtext" style="color: black;">用户名：</label>
            <input type="text" placeholder="请输入用户名" id="inputtext" v-model="searchUsername">
          </div>
          <button class="search-button" @click="fetchUsers">搜索</button>
          <button class="reset-button" @click="resetSearch">重置</button>
        </div>
        <div class="actions">
          <button class="delete-button" @click="handleBatchDelete">批量注销</button>
        </div>
      </div>
  
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
  
      <div v-else-if="users.length === 0" class="empty-container">
        <el-empty description="暂无数据" />
      </div>
  
      <table v-else class="user-table">
        <thead>
          <tr>
            <th>
              <input type="checkbox" 
                     :checked="isAllSelected" 
                     @change="toggleSelectAll">
            </th>
            <th class="sortable" @click="handleSort('uId')">
              ID {{ getSortIcon('uId') }}
            </th>
            <th>用户名</th>
            <th>手机号</th>
            <th class="sortable" @click="handleSort('createdAt')">
              创建时间 {{ getSortIcon('createdAt') }}
            </th>
            <th class="sortable" @click="handleSort('updatedAt')">
              更新时间 {{ getSortIcon('updatedAt') }}
            </th>
            <th class="sortable" @click="handleSort('usersStatus')">
              状态 {{ getSortIcon('usersStatus') }}
            </th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.uId">
            <td>
              <input type="checkbox" 
                     v-model="selectedUsers" 
                     :value="user.uId">
            </td>
            <td>{{ user.uId }}</td>
            <td>{{ user.uName }}</td>
            <td>{{ user.phone }}</td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td>{{ formatDate(user.updatedAt) }}</td>
            <td>
              <span :class="getStatusClass(user.usersStatus)">
                {{ getStatusText(user.usersStatus) }}
              </span>
            </td>
            <td class="actions-column">
              <button class="action-button edit" @click="handleEdit(user)">编辑</button>
              <button class="action-button delete" @click="handleSingleDelete(user.uId)">注销</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑用户状态"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="edit-form">
        <div class="form-item">
          <label>用户ID：</label>
          <span>{{ currentUser?.uId }}</span>
        </div>
        <div class="form-item">
          <label>用户名：</label>
          <span>{{ currentUser?.uName }}</span>
        </div>
        <div class="form-item">
          <label>用户状态：</label>
          <el-select v-model="selectedStatus" placeholder="请选择状态">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateStatus" :loading="updating">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { userApi } from '../api/console';
  
  interface User {
    uId: number;
    uName: string;
    phone: string;
    usersStatus: string;
    createdAt: number;
    updatedAt: number;
  }
  
  const users = ref<User[]>([]);
  const loading = ref(false);
  const startDate = ref('');
  const endDate = ref('');
  const searchUsername = ref('');
  
  // 选中的用户ID数组
  const selectedUsers = ref<number[]>([]);
  
  // 计算是否全选
  const isAllSelected = computed(() => {
    return users.value.length > 0 && selectedUsers.value.length === users.value.length;
  });
  
  // 切换全选
  const toggleSelectAll = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.checked) {
      selectedUsers.value = users.value.map(user => user.uId);
    } else {
      selectedUsers.value = [];
    }
  };
  
  // 排序相关
  type SortField = 'uId' | 'createdAt' | 'updatedAt' | 'usersStatus';
  type SortOrder = 'asc' | 'desc';
  const currentSort = ref<{ field: SortField; order: SortOrder }>({
    field: 'uId',
    order: 'asc'
  });
  
  // 处理排序
  const handleSort = (field: SortField) => {
    if (currentSort.value.field === field) {
      // 如果点击的是当前排序字段，切换排序顺序
      currentSort.value.order = currentSort.value.order === 'asc' ? 'desc' : 'asc';
    } else {
      // 如果点击的是新字段，设置为升序
      currentSort.value = { field, order: 'asc' };
    }
    sortUsers();
  };
  
  // 排序用户列表
  const sortUsers = () => {
    users.value.sort((a, b) => {
      let comparison = 0;
      switch (currentSort.value.field) {
        case 'uId':
          comparison = a.uId - b.uId;
          break;
        case 'createdAt':
          comparison = a.createdAt - b.createdAt;
          break;
        case 'updatedAt':
          comparison = a.updatedAt - b.updatedAt;
          break;
        case 'usersStatus':
          comparison = a.usersStatus.localeCompare(b.usersStatus);
          break;
      }
      return currentSort.value.order === 'asc' ? comparison : -comparison;
    });
  };
  
  // 获取排序图标
  const getSortIcon = (field: SortField) => {
    if (currentSort.value.field !== field) return '↕';
    return currentSort.value.order === 'asc' ? '↑' : '↓';
  };
  
  // 获取用户列表
  const fetchUsers = async () => {
    try {
      loading.value = true;
      const params: Record<string, string> = {};
  
      // 分别处理开始时间和结束时间
      if (startDate.value) {
        params.startTime = `${startDate.value} 00:00:00`;
      }
      if (endDate.value) {
        params.endTime = `${endDate.value} 23:59:59`;
      }
  
      if (searchUsername.value) {
        params.uName = searchUsername.value.trim();
      }
  
      const response = await userApi.getUsers(params);
  
      console.log('请求参数:', params);
      console.log('响应数据:', response);
  
      if (response.code === 200) {
        users.value = response.data;
        sortUsers();
      } else {
        ElMessage.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      ElMessage.error('获取用户列表失败');
    } finally {
      loading.value = false;
    }
  };
  
  // 格式化日期为 yyyy-MM-dd 格式
  const formatDateForInput = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  // 重置搜索条件
  const resetSearch = () => {
    startDate.value = '';
    endDate.value = '';
    searchUsername.value = '';
    fetchUsers();
  };
  
  // 格式化时间戳
  const formatDate = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };
  
  // 获取状态显示文本
  const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
      'ACTIVE': '正常',
      'INACTIVE': '冻结',
      'DELETED': '注销'
    };
    return statusMap[status] || '未知状态';
  };
  
  // 获取状态样式类
  const getStatusClass = (status: string) => {
    const statusMap: Record<string, string> = {
      'ACTIVE': 'status-enabled',
      'INACTIVE': 'status-disabled',
      'DELETED': 'status-deleted'
    };
    return statusMap[status] || '';
  };
  
  // 检查用户是否已被注销
  const checkUsersDeleted = (userIds: number[]) => {
    return userIds.every(uId => {
      const user = users.value.find(u => u.uId === uId);
      return user?.usersStatus === 'DELETED';
    });
  };
  
  // 批量注销
  const handleBatchDelete = async () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请选择要注销的用户');
      return;
    }

    // 检查选中的用户是否都已被注销
    if (checkUsersDeleted(selectedUsers.value)) {
      ElMessage.warning('选中的用户都已被注销');
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确定要注销选中的 ${selectedUsers.value.length} 个用户吗？`,
        '批量注销确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );

      const response = await userApi.batchDeleteUsers(selectedUsers.value);

      if (response.code === 200) {
        ElMessage.success('批量注销成功');
        // 清空选中状态
        selectedUsers.value = [];
        // 重新获取用户列表
        await fetchUsers();
      } else {
        ElMessage.error(response.message || '批量注销失败');
      }
    } catch (error) {
      if (error === 'cancel') {
        return;
      }
      console.error('批量注销失败:', error);
      ElMessage.error('批量注销失败，请稍后重试');
    }
  };
  
  // 单个注销
  const handleSingleDelete = async (uId: number) => {
    // 检查用户是否已被注销
    if (checkUsersDeleted([uId])) {
      ElMessage.warning('该用户已被注销');
      return;
    }

    try {
      await ElMessageBox.confirm(
        '确定要注销该用户吗？',
        '注销确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );

      const response = await userApi.batchDeleteUsers([uId]);

      if (response.code === 200) {
        ElMessage.success('注销成功');
        // 重新获取用户列表
        await fetchUsers();
      } else {
        ElMessage.error(response.message || '注销失败');
      }
    } catch (error) {
      if (error === 'cancel') {
        return;
      }
      console.error('注销失败:', error);
      ElMessage.error('注销失败，请稍后重试');
    }
  };
  
  // 编辑对话框相关
  const dialogVisible = ref(false);
  const currentUser = ref<User | null>(null);
  const selectedStatus = ref('');
  const updating = ref(false);
  
  // 状态选项
  const statusOptions = [
    { value: 'ACTIVE', label: '正常' },
    { value: 'INACTIVE', label: '冻结' },
    { value: 'DELETED', label: '注销' }
  ];
  
  // 打开编辑对话框
  const handleEdit = (user: User) => {
    currentUser.value = user;
    selectedStatus.value = user.usersStatus;
    dialogVisible.value = true;
  };
  
  // 更新用户状态
  const handleUpdateStatus = async () => {
    if (!currentUser.value) return;

    try {
      updating.value = true;
      const response = await userApi.updateUserStatus(
        currentUser.value.uId,
        {
          ...currentUser.value,
          usersStatus: selectedStatus.value
        }
      );

      if (response.code === 200) {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        // 重新获取用户列表
        await fetchUsers();
      } else {
        ElMessage.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新用户状态失败:', error);
      ElMessage.error('更新失败，请稍后重试');
    } finally {
      updating.value = false;
    }
  };
  
  // 在组件挂载后获取数据
  onMounted(() => {
    fetchUsers();
  });
  
  </script>
  
  <style scoped>
  .user-list-container {
    margin-left: 200px;
    margin-top: 45px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .search-filters {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .filter-item label {
    margin-right: 5px;
  }
  
  .filter-item input[type="date"],
  .filter-item input[type="text"] {
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  
  .search-button {
    padding: 8px 15px;
    background-color: #09b4c5;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .search-button:hover {
    background-color: #0795a5;
  }
  
  .actions button {
    padding: 8px 15px;
    margin-left: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .delete-button {
    background-color: #dc3545;
    color: #fff;
  }
  
  .delete-button:hover {
    background-color: #c82333;
  }
  
  .user-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
  }
  
  .user-table th,
  .user-table td {
    border: 1px solid #ddd;
    padding: 10px;
    text-align: center;
    color: #333;
    vertical-align: middle;
  }
  
  .user-table th {
    background-color: #f2f2f2;
    font-weight: bold;
    color: #333;
  }
  
  .user-table tbody tr:nth-child(even) {
    background-color: #f9f9f9;
  }
  
  .user-table tbody tr:hover {
    background-color: #f5f5f5;
  }
  
  .status-enabled {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #28a745;
    color: #fff;
  }
  
  .status-disabled {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #ffc107;
    color: #fff;
  }
  
  .status-deleted {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    background-color: #dc3545;
    color: #fff;
  }
  
  .actions-column {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    min-width: 200px;
    padding: 10px !important;
  }
  
  .action-button {
    padding: 4px 8px;
    border: 1px solid #007bff;
    background-color: #fff;
    color: #007bff;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    white-space: nowrap;
    margin: 0;
  }
  
  .actions-column button:hover {
    background-color: #007bff;
    color: #fff;
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #666;
  }
  
  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #09b4c5;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .reset-button {
    padding: 8px 15px;
    background-color: #6c757d;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    margin-left: 10px;
  }
  
  .reset-button:hover {
    background-color: #5a6268;
  }
  
  .sortable {
    cursor: pointer;
    user-select: none;
    position: relative;
  }
  
  .sortable:hover {
    background-color: #e6e6e6;
  }
  
  .empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
    background-color: #fff;
    border-radius: 8px;
    margin-top: 20px;
  }
  
  /* 添加复选框样式 */
  input[type="checkbox"] {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  
  .action-button.delete {
    border-color: #dc3545;
    color: #dc3545;
  }
  
  .action-button.delete:hover {
    background-color: #dc3545;
    color: #fff;
  }
  
  .action-button.edit {
    border-color: #28a745;
    color: #28a745;
  }
  
  .action-button.edit:hover {
    background-color: #28a745;
    color: #fff;
  }
  
  .edit-form {
    padding: 20px;
  }
  
  .form-item {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
  
  .form-item label {
    width: 80px;
    color: #666;
  }
  
  .form-item span {
    color: #333;
    margin-right: 20px;
  }
  
  .form-item .el-select {
    width: 200px;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  </style>